import React, { Component } from 'react'
import './AppRegister.scss'
import { user_register } from '../utils/api'
import { Toast } from 'antd-mobile'
export default class AppRegister extends Component {
  constructor(props) {
    super(props);
    this.state = {
      phone: '',
      pass: '',
      isRead: false
    }
  }
  handleChange(e) {
    this.setState({
      [e.target.name]: ((e.target.type === 'checkbox' || e.target.type === 'radio') ? e.target.checked : e.target.value)
    })
  }
  register() {
    if (/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/.test(this.state.phone) === false) {
      Toast.show({
        content: '请输入合法手机号！',
      })
    } else if (this.state.pass === '') {
      Toast.show({
        content: '请输入密码！',
      })
    } else if (this.state.isRead === false) {
      Toast.show({
        content: '请仔细阅读协议后在注册！',
      })
    }
    else {
      user_register(this.state).then((res) => {
        console.log(res)
        if (res.data.code === 200) {
          //保存用户信息,token
          localStorage.setItem('token', res.data.token);
          localStorage.setItem('userinfo', JSON.stringify(res.data.userinfo));
          //  弹出 轻提示
          Toast.show({
            content: res.data.msg,
            icon: 'success'
          })
          this.props.history.push({ pathname: '/index/Register' })
        } else {
          //  弹出 轻提示
          Toast.show({
            content: res.data.msg,
            icon: 'fail'
          })
        }
      })
    }

  }
  render() {
    return (
      <div className='AppRegister'>
        <div className="box">
          <div className='head'>注册页</div>
          <div className='mainIpt'>
            <input type="text" placeholder='用户名'
              name='phone'
              value={this.state.phone} onChange={(e) => { this.handleChange(e) }} />
            <input type="password" placeholder='密码' name='pass' value={this.state.pass} onChange={(e) => { this.handleChange(e) }} />
            <div className="ck">
              <input type="checkbox" name='isRead' checked={this.state.isRead} onChange={(e) => { this.handleChange(e) }} /><a href="#">请仔细阅读用户协议</a>
            </div>
          </div>
          <button onClick={() => { this.register() }}>注册</button>
        </div>
      </div>
    )
  }
}
